package com.yidi.system.service.imp;

import com.yidi.common.annotation.DataScope;
import com.yidi.common.constant.UserConstants;
import com.yidi.common.core.domain.AjaxResult;
import com.yidi.common.core.domain.entity.SysMenu;
import com.yidi.common.core.domain.entity.SysRole;
import com.yidi.common.core.domain.entity.SysUser;
import com.yidi.common.core.page.MyPage;
import com.yidi.common.core.service.imp.AbstractBaseService;
import com.yidi.common.core.text.Convert;
import com.yidi.common.enums.RemoveEnum;
import com.yidi.common.exception.ServiceException;
import com.yidi.common.utils.SecurityUtils;
import com.yidi.common.utils.StringUtils;
import com.yidi.common.utils.spring.SpringUtils;

import com.yidi.system.domain.SysRoleDept;
import com.yidi.system.domain.SysRoleMenu;
import com.yidi.system.domain.SysUserRole;
import com.yidi.system.repository.SysRoleRepository;
import com.yidi.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.Predicate;
import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author ：Xn
 * @ClassName: SysRoleServiceImpl
 * @date ：2021-10-19 14:39
 * @describe ：
 */
@Service
public class SysRoleServiceImpl extends AbstractBaseService<SysRole> implements SysRoleService {

    @Autowired
    private SysRoleRepository sysRoleRepository;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRoleMenuService sysRoleMenuService;
    @Autowired
    private SysRoleDeptService sysRoleDeptService;
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @PersistenceContext
    private EntityManager em;

    /**
     * 分页
     */
    @Override
    @DataScope(deptAlias = "d")
    public MyPage<SysRole> findByPage(SysRole role, Integer pageNo, Integer pageSize) {
        StringBuilder sql = new StringBuilder(
                "select distinct r.id, r.role_name, r.role_key, r.order_num, r.data_scope, r.menu_check_strictly, r.dept_check_strictly, r.status, r.remove_status, r.create_time" +
                        " from sys_role r" +
                        " left join sys_user_role ur on ur.role_id = r.id" +
                        " left join sys_user u on u.id = ur.user_id" +
                        " left join sys_dept d on u.dept_id = d.id" +
                        " where r.remove_status = 0");

        if(role.getId() != null){
            sql.append(" and r.id = ").append(role.getId());
        }

        if(StringUtils.isNotBlank(role.getRoleName())){
            sql.append(" and r.role_name like concat('%', '").append(role.getRoleName()).append("', '%')");
        }

        if(StringUtils.isNotBlank(role.getStatus())){
            sql.append(" and r.status = '").append(role.getStatus()).append("'");
        }

        if(StringUtils.isNotBlank(role.getRoleKey())){
            sql.append(" and r.role_key like concat('%', '").append(role.getRoleKey()).append("', '%')");
        }

        if(role.getParams() != null){
            Map<String, Object> params = role.getParams();
            String beginTime = (String) params.get("beginTime");
            String endTime = (String) params.get("endTime");
            String sqlString = (String)params.get("dataScope");

            if(StringUtils.isNotBlank(beginTime)){
                sql.append(" and date_format(r.create_time,'%y%m%d') >= date_format('").append(beginTime).append("','%y%m%d')");
            }
            if(StringUtils.isNotBlank(endTime)){
                sql.append(" and date_format(r.create_time,'%y%m%d') <= date_format('").append(endTime).append("','%y%m%d')");
            }
            if(StringUtils.isNotBlank(sqlString)){
                sql.append(sqlString);
            }
        }
        Query query = em.createNativeQuery(sql.toString());
        int firstIndex = pageNo * pageSize;
        query.setFirstResult(firstIndex);
        query.setMaxResults(pageSize);
        List<Object[]> list = query.getResultList();
        String countSql = "select count(*) from ("+sql.toString()+") c";
        Query countQuery = em.createNativeQuery(countSql);
        Object obj = countQuery.getSingleResult();
        Integer tatal = Integer.parseInt(obj.toString());
        BigDecimal bd = BigDecimal.valueOf(tatal);
        BigDecimal bdsize = BigDecimal.valueOf(pageSize);
        BigDecimal bdvi = bd.divide(bdsize, 1, BigDecimal.ROUND_HALF_UP);
        Integer totalPage = (int)Math.ceil(bdvi.doubleValue());
        List<SysRole> roleList = new ArrayList<SysRole>();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        for(Object[] objects : list){
            SysRole r = new SysRole();
            r.setId(Long.parseLong(objects[0].toString()));
            r.setRoleName(objects[1].toString());
            r.setRoleKey(objects[2].toString());
            r.setOrderNum(Integer.parseInt(objects[3].toString()));
            r.setDataScope(objects[4].toString());
            r.setMenuCheckStrictly(Boolean.valueOf(objects[5].toString()));
            r.setDeptCheckStrictly(Boolean.valueOf(objects[6].toString()));
            r.setStatus(objects[7].toString());
            r.setRemoveStatus(Integer.parseInt(objects[8].toString()));
            try {
                r.setCreateTime(format.parse(objects[9].toString()));
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            roleList.add(r);
        }

        MyPage<SysRole> page = new MyPage<SysRole>(pageNo,totalPage,roleList,new  com.yidi.common.core.page.Pageable(pageSize),tatal+"",tatal);

        return page;
    }

    /**
     * 校验角色是否有数据权限
     *
     * @param roleId 角色id
     */
    @Override
    public void checkRoleDataScope(Long roleId)
    {
        Long userId = SecurityUtils.getUserId();
        SysUser user = sysUserService.findById(userId);
        if (!SysUser.isAdmin(user.getUserName()))
        {
            SysRole role = new SysRole();
            role.setId(roleId);
            List<SysRole> roles = SpringUtils.getAopProxy(this).findByPage(role,0,Integer.MAX_VALUE).getContent();
            if (StringUtils.isEmpty(roles))
            {
                throw new ServiceException("没有权限访问角色数据！");
            }
        }
    }

    /**
     * 校验角色名称是否唯一
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    public String checkRoleNameUnique(SysRole role)
    {
        Long roleId = StringUtils.isNull(role.getId()) ? -1L : role.getId();
        SysRole info = sysRoleRepository.findByRoleName(role.getRoleName());
        if (StringUtils.isNotNull(info) && !info.getId().equals(roleId))
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验角色权限是否唯一
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    public String checkRoleKeyUnique(SysRole role)
    {
        Long roleId = StringUtils.isNull(role.getId()) ? -1L : role.getId();
        SysRole info = sysRoleRepository.findByRoleKey(role.getRoleKey());
        if (StringUtils.isNotNull(info) && !info.getId().equals(roleId))
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 新增保存角色信息
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    @Transactional
    public void insertRole(SysRole role)
    {
        // 新增角色信息
        add(role);
        insertRoleMenu(role);
    }

    /**
     * 校验角色是否允许操作
     *
     * @param role 角色信息
     */
    @Override
    public void checkRoleAllowed(SysRole role)
    {
        if (StringUtils.isNotNull(role.getId()) && role.isAdmin())
        {
            throw new ServiceException("不允许操作超级管理员角色");
        }
    }

    /**
     * 修改保存角色信息
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    @Transactional
    public void updateRole(SysRole role)
    {
        SysRole r = findById(role.getId());
        r.setRoleName(role.getRoleName());
        r.setRoleKey(role.getRoleKey());
        r.setOrderNum(role.getOrderNum());
        r.setStatus(role.getStatus());
        r.setRemark(role.getRemark());
        // 修改角色信息
        modify(r);
        // 删除角色与菜单关联
        sysRoleMenuService.deleteRoleMenuByRoleId(role.getId());
        insertRoleMenu(role);
    }

    /**
     * 修改数据权限信息
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    @Transactional
    public void authDataScope(SysRole role)
    {
        // 修改角色信息
        SysRole r = findById(role.getId());
        r.setDataScope(role.getDataScope());
        // 修改角色信息
        modify(r);
        // 删除角色与部门关联
        sysRoleDeptService.deleteRoleDeptByRoleId(role.getId());
        // 新增角色和部门信息（数据权限）
       insertRoleDept(role);
    }

    /**
     * 修改状态
     * @param role
     */
    @Override
    public void updateRoleStatus(SysRole role){
        SysRole sr = findById(role.getId());
        sr.setStatus(role.getStatus());
        modify(sr);
    }

    /**
     * 批量删除角色信息
     *
     * @param roleIds 需要删除的数据ID
     * @throws Exception
     */
    @Override
    public void deleteRoleByIds(Long[] roleIds)
    {
        for (Long roleId : roleIds)
        {
            checkRoleAllowed(new SysRole(roleId));
            SysRole role = findById(roleId);
            if (countUserRoleByRoleId(roleId) > 0)
            {
                throw new ServiceException(String.format("%1$s已分配,不能删除", role.getRoleName()));
            }
        }
        // 删除角色与菜单关联
        sysRoleMenuService.deleteRoleMenu(roleIds);
        // 删除角色与部门关联
        sysRoleDeptService.deleteRoleDept(roleIds);
        for(Long roleId : roleIds){
            delete(roleId);
        }
    }

    /**
     * 通过角色ID查询角色使用数量
     *
     * @param roleId 角色ID
     * @return 结果
     */
    @Override
    public int countUserRoleByRoleId(Long roleId)
    {
        return sysUserRoleService.countUserRoleByRoleId(roleId);
    }

    @Override
    public void deleteAuthUser(SysUserRole userRole){
        sysUserRoleService.deleteUserRoleInfo(userRole.getUserId(), userRole.getRoleId());
    }

    @Override
    public void deleteAuthUsers(Long roleId, Long[] userIds){
        for(Long id : userIds){
            sysUserRoleService.deleteUserRoleInfo(id, roleId);
        }
    }

    @Override
    public void insertAuthUsers(Long roleId, Long[] userIds){
        // 新增用户与角色管理
        List<SysUserRole> list = new ArrayList<SysUserRole>();
        for (Long userId : userIds)
        {
            SysUserRole ur = new SysUserRole();
            ur.setUserId(userId);
            ur.setRoleId(roleId);
            list.add(ur);
        }

        for(SysUserRole ur : list){
            sysUserRoleService.add(ur);
        }
    }

    /**
     * 根据用户ID获取角色选择框列表
     *
     * @param userId 用户ID
     * @return 选中角色ID列表
     */
    @Override
    public List<Long> selectRoleListByUserId(Long userId)
    {
        return sysRoleRepository.selectRoleListByUserId(userId);
    }

    /**
     * 根据用户ID查询权限
     *
     * @param userId 用户ID
     * @return 权限列表
     */
    @Override
    public Set<String> selectRolePermissionByUserId(Long userId)
    {
        List<SysRole> perms = findRolePermissionByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (SysRole perm : perms)
        {
            if (StringUtils.isNotNull(perm))
            {
                permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(",")));
            }
        }
        return permsSet;
    }

    /**
     * 根据用户ID查询角色
     *
     * @param userId 用户ID
     * @return 角色列表
     */
    @Override
    public List<SysRole> selectRolesByUserId(Long userId)
    {
        List<SysRole> userRoles = findRolePermissionByUserId(userId);
        List<SysRole> roles = findAllByRs(RemoveEnum.NOT_REMOVE.getCode());
        for (SysRole role : roles)
        {
            for (SysRole userRole : userRoles)
            {
                if (role.getId().equals(userRole.getId()))
                {
                    role.setFlag(true);
                    break;
                }
            }
        }
        return roles;
    }


    public List<SysRole> findRolePermissionByUserId(Long userId){
        List<Map<String, Object>> maps = sysRoleRepository.selectRolePermissionByUserId(userId);
        return mapChangeMenus(maps);
    }

    public List<SysRole> mapChangeMenus(List<Map<String, Object>> menuMap){

        List<SysRole> roleList = new LinkedList<SysRole>();

        for(int i = 0; i < menuMap.size(); i++) {
            Map<String, Object> map = menuMap.get(i);
            SysRole r = new SysRole();
            r.setId(Long.valueOf(String.valueOf(map.get("id"))));
            r.setRoleName(String.valueOf(map.get("roleName")));
            r.setRoleKey(String.valueOf(map.get("roleKey")));
            r.setOrderNum(Integer.valueOf(String.valueOf(map.get("orderNum"))));
            r.setDataScope(String.valueOf(map.get("dataScope")));
            r.setMenuCheckStrictly(Boolean.valueOf(String.valueOf(map.get("menuCheckStrictly"))));
            r.setDeptCheckStrictly(Boolean.valueOf(String.valueOf(map.get("deptCheckStrictly"))));
            r.setStatus(String.valueOf(map.get("status")));
            r.setRemoveStatus(Integer.valueOf(String.valueOf(map.get("removeStatus"))));
            r.setRemark(String.valueOf(map.get("remark")));

            roleList.add(r);
        }

        return roleList;
    }
    /**
     * 新增角色菜单信息
     *
     * @param role 角色对象
     */
    public void insertRoleMenu(SysRole role)
    {
        // 新增用户与角色管理
        List<SysRoleMenu> list = new ArrayList<SysRoleMenu>();
        for (Long menuId : role.getMenuIds())
        {
            SysRoleMenu rm = new SysRoleMenu();
            rm.setRoleId(role.getId());
            rm.setMenuId(menuId);
            list.add(rm);
        }
        if (list.size() > 0)
        {
            sysRoleMenuService.batchRoleMenu(list);
        }
    }

    /**
     * 新增角色部门信息(数据权限)
     *
     * @param role 角色对象
     */
    public void insertRoleDept(SysRole role)
    {
        int rows = 1;
        // 新增角色与部门（数据权限）管理
        List<SysRoleDept> list = new ArrayList<SysRoleDept>();
        for (Long deptId : role.getDeptIds())
        {
            SysRoleDept rd = new SysRoleDept();
            rd.setRoleId(role.getId());
            rd.setDeptId(deptId);
            list.add(rd);
        }
        sysRoleDeptService.batchRoleDept(list);
    }
}
